package com.heima.search.service.impl;


import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.aliyuncs.unmarshaller.JsonUnmashaller;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.search.pojos.ApAssociateWords;
import com.heima.search.bean.AssociateBean;
import com.heima.search.service.AssociateService;
import org.eclipse.parsson.JsonUtil;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;


@Service
public class AssociateServiceImpl implements AssociateService {
    @Override
    public List<ApAssociateWords> associate(UserSearchDto userSearchDto) {
        HttpResponse response = HttpRequest.get(StrUtil.format("https://www.baidu.com/sugrec?prod=pc&wd={}", userSearchDto.getSearchWords()))
                .timeout(20000)
                .execute();

        List<ApAssociateWords> associateWords = null;
        if (response.isOk()){
            String body = response.body();
            JSONObject jsonObject = JSONUtil.parseObj(body);
            // 进一步处理数据
            String data = jsonObject.getStr("g");
            List<AssociateBean> associateBeans = JSONUtil.toList(data, AssociateBean.class);
            associateWords = associateBeans.stream()
                    .map(AssociateBean::getQ)
                    .map(s -> {
                        ApAssociateWords associateWords1 = new ApAssociateWords();
                        associateWords1.setAssociateWords(s);
                        return associateWords1;
                    })
                    .collect(Collectors.toList());
            System.out.println("Extracted data: " + data);
        }

        return associateWords;
    }
}
